<template>
  <div>
    <Navbar />
    <div class="checkout-container">
      <div class="checkout-content">
        <el-steps :active="currentStep" finish-status="success" align-center>
          <el-step title="确认商品"></el-step>
          <el-step title="填写订单"></el-step>
          <el-step title="完成支付"></el-step>
        </el-steps>

        <!-- 步骤1: 确认商品 -->
        <div v-if="currentStep === 0" class="step-content">
          <el-card class="order-card">
            <template #header>
              <h3>确认订单商品</h3>
            </template>
            
            <div class="product-list">
              <div v-for="item in cartItems" :key="item.productId" class="product-item">
                <div class="product-info">
                  <el-icon class="product-icon"><Cpu /></el-icon>
                  <div class="product-details">
                    <h4>{{ item.productName }}</h4>
                    <p class="product-spec">{{ item.specParams }}</p>
                    <div class="product-price">
                      <span class="price">¥{{ item.price }}</span>
                      <span class="quantity">× {{ item.quantity }}</span>
                    </div>
                  </div>
                </div>
                <div class="item-total">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              </div>
            </div>
            
            <div class="order-summary">
              <div class="summary-row">
                <span>商品总价：</span>
                <span>¥{{ totalAmount.toFixed(2) }}</span>
              </div>
              <div class="summary-row">
                <span>运费：</span>
                <span>免费</span>
              </div>
              <div class="summary-row total">
                <span>应付总额：</span>
                <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
              </div>
            </div>
            
            <div class="step-actions">
              <el-button @click="$router.push('/cart')">返回购物车</el-button>
              <el-button type="primary" @click="nextStep">确认商品</el-button>
            </div>
          </el-card>
        </div>

        <!-- 步骤2: 填写订单信息 -->
        <div v-if="currentStep === 1" class="step-content">
          <el-row :gutter="20">
            <el-col :span="16">
              <!-- 收货地址 -->
              <el-card class="address-card">
                <template #header>
                  <div class="card-header">
                    <h3>收货地址</h3>
                    <el-button type="primary" size="small" @click="showAddressDialog = true">
                      添加新地址
                    </el-button>
                  </div>
                </template>
                
                <div v-if="addresses.length === 0" class="no-address">
                  <p>您还没有收货地址，请先添加地址</p>
                </div>
                
                <el-radio-group v-model="selectedAddressId" class="address-list">
                  <div class="address-item" v-for="address in addresses" :key="address.addressId">
                    <el-radio :value="address.addressId" class="address-radio">
                      <div class="address-content">
                        <div class="address-header">
                          <span class="contact-info">{{ address.contactName }} {{ address.contactPhone }}</span>
                          <el-tag v-if="address.isDefault" type="success" size="small">默认</el-tag>
                        </div>
                        <div class="address-detail">{{ address.address }}</div>
                      </div>
                    </el-radio>
                  </div>
                </el-radio-group>
              </el-card>

              <!-- 支付方式 -->
              <el-card class="payment-card">
                <template #header>
                  <h3>支付方式</h3>
                </template>
                
                <div class="payment-methods">
                  <div 
                    v-for="method in paymentOptions" 
                    :key="method.value"
                    class="payment-option"
                    :class="{ 'selected': paymentMethod === method.value }"
                    @click="selectPaymentMethod(method.value)"
                  >
                    <div class="payment-radio">
                      <div class="radio-circle" :class="{ 'checked': paymentMethod === method.value }">
                        <div v-if="paymentMethod === method.value" class="radio-dot"></div>
                      </div>
                    </div>
                    <div class="payment-icon">
                      <i :class="method.icon"></i>
                    </div>
                    <div class="payment-info">
                      <div class="payment-name">{{ method.name }}</div>
                      <div class="payment-desc">{{ method.desc }}</div>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>

            <el-col :span="8">
              <!-- 订单汇总 -->
              <el-card class="summary-card">
                <template #header>
                  <h3>订单汇总</h3>
                </template>
                
                <div class="order-summary">
                  <div class="summary-row">
                    <span>商品数量：</span>
                    <span>{{ totalQuantity }}件</span>
                  </div>
                  <div class="summary-row">
                    <span>商品总价：</span>
                    <span>¥{{ totalAmount.toFixed(2) }}</span>
                  </div>
                  <div class="summary-row">
                    <span>运费：</span>
                    <span>免费</span>
                  </div>
                  <div class="summary-row total">
                    <span>应付总额：</span>
                    <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button 
              type="primary" 
              @click="createOrder"
              :disabled="!selectedAddressId || !paymentMethod"
              :loading="creating"
            >
              提交订单
            </el-button>
          </div>
        </div>

        <!-- 步骤3: 支付页面 -->
        <div v-if="currentStep === 2" class="step-content">
          <el-card class="payment-card">
            <template #header>
              <h3>订单支付</h3>
            </template>
            
            <div class="payment-info">
              <div class="order-info">
                <p><strong>订单号：</strong>{{ currentOrder?.orderId || '生成中...' }}</p>
                <p><strong>支付方式：</strong>{{ paymentMethod }}</p>
                <p><strong>支付金额：</strong><span class="pay-amount">¥{{ totalAmount.toFixed(2) }}</span></p>
              </div>
              
              <div class="payment-qr">
                <div class="qr-placeholder">
                  <el-icon size="80"><Cpu /></el-icon>
                  <p>请使用{{ paymentMethod }}扫码支付</p>
                </div>
              </div>
              
              <div class="payment-actions">
                <el-button type="success" size="large" @click="confirmPayment" :loading="paying">
                  我已完成支付
                </el-button>
                <el-button @click="cancelOrder">取消订单</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 添加地址对话框 -->
    <el-dialog v-model="showAddressDialog" title="添加收货地址" width="500px">
      <el-form :model="newAddress" :rules="addressRules" ref="addressForm" label-width="80px">
        <el-form-item label="收货人" prop="contactName">
          <el-input v-model="newAddress.contactName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="contactPhone">
          <el-input v-model="newAddress.contactPhone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input 
            v-model="newAddress.address" 
            type="textarea" 
            :rows="3"
            placeholder="请输入详细收货地址" 
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="newAddress.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddressDialog = false">取消</el-button>
        <el-button type="primary" @click="addAddress" :loading="addingAddress">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Cpu } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'
import { orderAPI, addressAPI } from '@/api'

export default {
  name: 'CheckoutView',
  components: {
    Navbar,
    Cpu
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const currentStep = ref(0)
    const creating = ref(false)
    const paying = ref(false)
    const showAddressDialog = ref(false)
    const addingAddress = ref(false)
    const addressForm = ref()
    
    const selectedAddressId = ref(null)
    const paymentMethod = ref('支付宝')
    const addresses = ref([])
    const currentOrder = ref({})
    
    // 支付方式选项
    const paymentOptions = ref([
      {
        value: '支付宝',
        name: '支付宝',
        desc: '推荐使用支付宝支付',
        icon: 'fab fa-alipay'
      },
      {
        value: '微信支付',
        name: '微信支付',
        desc: '使用微信扫码支付',
        icon: 'fab fa-weixin'
      },
      {
        value: '银行卡',
        name: '银行卡支付',
        desc: '支持各大银行借记卡和信用卡',
        icon: 'fas fa-credit-card'
      }
    ])
    
    const newAddress = reactive({
      contactName: '',
      contactPhone: '',
      address: '',
      isDefault: false
    })
    
    const addressRules = {
      contactName: [
        { required: true, message: '请输入收货人姓名', trigger: 'blur' }
      ],
      contactPhone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入详细地址', trigger: 'blur' }
      ]
    }
    
    // 从store获取购物车商品
    const cartItems = computed(() => store.state.cart || [])
    
    // 计算总数量
    const totalQuantity = computed(() => {
      return cartItems.value.reduce((total, item) => total + item.quantity, 0)
    })
    
    // 计算总金额
    const totalAmount = computed(() => {
      return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
    })
    
    // 获取用户地址
    const loadAddresses = async () => {
      try {
        const user = store.state.user
        if (!user) {
          ElMessage.error('请先登录')
          router.push('/login')
          return
        }
        
        const response = await addressAPI.getUserAddresses(user.userId)
        addresses.value = response.data || []
        
        // 自动选择默认地址
        const defaultAddress = addresses.value.find(addr => addr.isDefault)
        if (defaultAddress) {
          selectedAddressId.value = defaultAddress.addressId
        }
      } catch (error) {
        console.error('获取地址失败:', error)
      }
    }
    
    // 添加地址
    const addAddress = async () => {
      try {
        await addressForm.value.validate()
        addingAddress.value = true
        
        const user = store.state.user
        const addressData = {
          ...newAddress,
          userId: user.userId
        }
        
        await addressAPI.addAddress(addressData)
        ElMessage.success('地址添加成功')
        showAddressDialog.value = false
        
        // 重置表单
        Object.assign(newAddress, {
          contactName: '',
          contactPhone: '',
          address: '',
          isDefault: false
        })
        
        // 重新加载地址列表
        await loadAddresses()
      } catch (error) {
        console.error('添加地址失败:', error)
        ElMessage.error('添加地址失败')
      } finally {
        addingAddress.value = false
      }
    }
    
    // 下一步
    const nextStep = () => {
      if (currentStep.value < 2) {
        currentStep.value++
      }
    }
    
    // 上一步
    const prevStep = () => {
      if (currentStep.value > 0) {
        currentStep.value--
      }
    }
    
    // 选择支付方式
    const selectPaymentMethod = (method) => {
      paymentMethod.value = method
    }
    
    // 创建订单
    const createOrder = async () => {
      try {
        creating.value = true
        
        const user = store.state.user
        const selectedAddress = addresses.value.find(addr => addr.addressId === selectedAddressId.value)
        
        if (!selectedAddress) {
          ElMessage.error('请选择收货地址')
          return
        }
        
        const orderData = {
          userId: user.userId,
          totalAmount: totalAmount.value,
          shippingAddress: selectedAddress.address,
          contactInfo: `${selectedAddress.contactName} ${selectedAddress.contactPhone}`,
          paymentMethod: paymentMethod.value,
          orderDetails: cartItems.value.map(item => ({
            productId: item.productId,
            quantity: item.quantity,
            unitPrice: item.price
          }))
        }
        
        const response = await orderAPI.createOrder(orderData)
        
        // 处理不同的响应格式
        if (response.data) {
          currentOrder.value = response.data
        } else if (response.order) {
          currentOrder.value = response.order
        } else if (response.orderId) {
          currentOrder.value = response
        } else {
          // 如果没有返回订单信息，创建一个临时订单对象
          currentOrder.value = {
            orderId: Date.now(), // 临时ID
            ...orderData
          }
        }
        
        console.log('创建的订单:', currentOrder.value)
        ElMessage.success('订单创建成功')
        nextStep()
      } catch (error) {
        console.error('创建订单失败:', error)
        ElMessage.error('创建订单失败')
      } finally {
        creating.value = false
      }
    }
    
    // 确认支付
    const confirmPayment = async () => {
      try {
        paying.value = true
        
        // 检查订单是否存在
        if (!currentOrder.value || !currentOrder.value.orderId) {
          ElMessage.error('订单信息不完整，请重新创建订单')
          currentStep.value = 1 // 回到创建订单步骤
          return
        }
        
        // 模拟支付过程
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        // 更新订单状态为已支付
        await orderAPI.updateOrderStatus(currentOrder.value.orderId, 'paid')
        
        // 清空购物车
        store.commit('clearCart')
        
        ElMessage.success('支付成功！')
        router.push('/orders')
      } catch (error) {
        console.error('支付失败:', error)
        ElMessage.error('支付失败')
      } finally {
        paying.value = false
      }
    }
    
    // 取消订单
    const cancelOrder = async () => {
      try {
        // 检查订单是否存在
        if (!currentOrder.value || !currentOrder.value.orderId) {
          ElMessage.error('订单信息不完整')
          return
        }
        
        await ElMessageBox.confirm('确定要取消订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await orderAPI.updateOrderStatus(currentOrder.value.orderId, 'cancelled')
        ElMessage.success('订单已取消')
        router.push('/cart')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单失败:', error)
          ElMessage.error('取消订单失败')
        }
      }
    }
    
    onMounted(() => {
      // 检查是否有商品
      if (cartItems.value.length === 0) {
        ElMessage.warning('购物车为空，请先添加商品')
        router.push('/products')
        return
      }
      
      // 检查用户登录状态
      if (!store.state.user) {
        ElMessage.error('请先登录')
        router.push('/login')
        return
      }
      
      loadAddresses()
    })
    
    return {
      currentStep,
      creating,
      paying,
      showAddressDialog,
      addingAddress,
      addressForm,
      selectedAddressId,
      paymentMethod,
      addresses,
      currentOrder,
      newAddress,
      addressRules,
      cartItems,
      totalQuantity,
      totalAmount,
      paymentOptions,
      selectPaymentMethod,
      addAddress,
      nextStep,
      prevStep,
      createOrder,
      confirmPayment,
      cancelOrder
    }
  }
}
</script>

<style scoped>
.checkout-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 50%, #16213e 100%);
  padding: 80px 20px 40px;
}

.checkout-content {
  max-width: 1200px;
  margin: 0 auto;
}

.el-steps {
  margin-bottom: 40px;
}

.step-content {
  margin-top: 30px;
}

.order-card,
.address-card,
.payment-card,
.summary-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #ffffff;
}

.product-list {
  margin-bottom: 20px;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.product-item:last-child {
  border-bottom: none;
}

.product-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.product-icon {
  font-size: 40px;
  color: #64b5f6;
  margin-right: 15px;
}

.product-details h4 {
  margin: 0 0 5px 0;
  color: #ffffff;
  font-size: 16px;
}

.product-spec {
  color: #b0bec5;
  font-size: 12px;
  margin: 0 0 8px 0;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price {
  color: #64b5f6;
  font-weight: bold;
}

.quantity {
  color: #b0bec5;
}

.item-total {
  color: #64b5f6;
  font-weight: bold;
  font-size: 16px;
}

.order-summary {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding-top: 15px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #b0bec5;
}

.summary-row.total {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding-top: 10px;
  margin-top: 10px;
}

.total-price {
  color: #64b5f6;
}

.step-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.step-actions .el-button {
  margin: 0 10px;
}

.no-address {
  text-align: center;
  padding: 40px;
  color: #b0bec5;
}

.address-list {
  width: 100%;
}

.address-item {
  width: 100%;
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.address-item:hover {
  border-color: #64b5f6;
}

.address-radio {
  width: 100%;
}

.address-content {
  width: 100%;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.contact-info {
  color: #ffffff;
  font-weight: bold;
}

.address-detail {
  color: #b0bec5;
  font-size: 14px;
}

.payment-methods {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.payment-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 20px 15px;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 140px;
}

.payment-option:hover {
  border-color: rgba(100, 181, 246, 0.5);
  background: rgba(100, 181, 246, 0.1);
}

.payment-option.selected {
  border-color: #00D4FF;
  background: rgba(0, 212, 255, 0.1);
  box-shadow: 0 0 20px rgba(0, 212, 255, 0.2);
}

.payment-radio {
  margin-bottom: 10px;
}

.radio-circle {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio-circle.checked {
  border-color: #00D4FF;
  background: rgba(0, 212, 255, 0.1);
}

.radio-dot {
  width: 8px;
  height: 8px;
  background: #00D4FF;
  border-radius: 50%;
}

.payment-icon {
  margin-bottom: 10px;
  font-size: 36px;
  color: #00D4FF;
}

.payment-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.payment-name {
  color: #ffffff;
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 5px;
}

.payment-desc {
  color: #b0bec5;
  font-size: 12px;
  line-height: 1.4;
}

.order-info {
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.order-info p {
  margin: 10px 0;
  color: #b0bec5;
}

.pay-amount {
  color: #64b5f6;
  font-size: 24px;
  font-weight: bold;
}

.payment-qr {
  text-align: center;
  margin: 40px 0;
}

.qr-placeholder {
  padding: 60px;
  border: 2px dashed rgba(255, 255, 255, 0.3);
  border-radius: 12px;
  color: #b0bec5;
}

.qr-placeholder p {
  margin-top: 20px;
  font-size: 16px;
}

.payment-actions {
  text-align: center;
  margin-top: 30px;
}

.payment-actions .el-button {
  margin: 0 10px;
}

/* Element Plus 样式覆盖 */
:deep(.el-steps) {
  .el-step__title {
    color: #b0bec5;
  }
  
  .el-step__title.is-finish,
  .el-step__title.is-process {
    color: #64b5f6;
  }
}

:deep(.el-card__header) {
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

:deep(.el-radio__label) {
  color: #ffffff;
}

:deep(.el-dialog) {
  background: rgba(26, 26, 46, 0.95);
  backdrop-filter: blur(10px);
}

:deep(.el-form-item__label) {
  color: #ffffff !important;
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

:deep(.el-input__inner) {
  color: #ffffff;
}

:deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #ffffff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .checkout-content {
    padding: 0 10px;
  }
  
  .product-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .item-total {
    align-self: flex-end;
  }
  
  .payment-methods {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .payment-option {
    flex-direction: row;
    text-align: left;
    min-height: auto;
    padding: 15px;
  }
  
  .payment-radio {
    margin-bottom: 0;
    margin-right: 15px;
  }
  
  .payment-icon {
    margin-bottom: 0;
    margin-right: 15px;
    font-size: 28px;
  }
  
  .payment-info {
    align-items: flex-start;
  }
}

@media (max-width: 1024px) and (min-width: 769px) {
  .payment-methods {
    grid-template-columns: 1fr 1fr;
    gap: 15px;
  }
}
</style> 